<template>
  <div class="admin-container">
    <div class="sidebar">
      <div class="sidebar-menu">
        <div class="menu-item" :class="{ active: currentTab === 'user' }" @click="currentTab = 'user'"><i class="icon-user"></i> 用户管理</div>
        <div class="menu-item" :class="{ active: currentTab === 'book' }" @click="currentTab = 'book'"><i class="icon-book"></i> 图书管理</div>
      </div>
    </div>
    <div class="main-content">
      <!-- 用户管理内容 -->
      <div v-if="currentTab === 'user'">
        <div class="page-header">
          <h1>用户管理</h1>
          <button class="btn-add" @click="openAddUserModal"><i class="icon-add"></i> 添加用户</button>
        </div>

        <div class="search-bar">
          <input type="text" v-model="searchKeyword" placeholder="搜索用户名或邮箱..." />
          <button class="btn-search" @click="fetchUsers"><i class="icon-search"></i> 搜索</button>
        </div>

        <div class="table-container">
          <table class="user-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>角色</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.id">
                <td>{{ user.id }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.role?.name || '未知角色' }}</td>
                <td>
                  <span :class="['status-badge', user.status === 'active' ? 'status-active' : 'status-inactive']">
                    {{ user.status === 'active' ? '启用' : '禁用' }}
                  </span>
                </td>
                <td class="action-buttons">
                  <button class="btn-edit" @click="openEditUserModal(user)"><i class="icon-edit"></i> 编辑</button>
                  <button class="btn-delete" @click="confirmDeleteUser(user.id)"><i class="icon-delete"></i> 删除</button>
                </td>
              </tr>
              <tr v-if="users.length === 0 && !userLoading">
                <td colspan="6" class="no-data">暂无用户数据</td>
              </tr>
              <tr v-if="userLoading">
                <td colspan="6" class="loading">加载中...</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="pagination" v-if="userTotalPages > 1">
          <button @click="changeUserPage(1)" :disabled="userCurrentPage === 1">首页</button>
          <button @click="changeUserPage(userCurrentPage - 1)" :disabled="userCurrentPage === 1">上一页</button>
          <span>第 {{ userCurrentPage }} 页 / 共 {{ userTotalPages }} 页</span>
          <button @click="changeUserPage(userCurrentPage + 1)" :disabled="userCurrentPage === userTotalPages">下一页</button>
          <button @click="changeUserPage(userTotalPages)" :disabled="userCurrentPage === userTotalPages">末页</button>
        </div>
      </div>

      <!-- 图书管理内容 -->
      <div v-if="currentTab === 'book'">
        <div class="page-header">
          <h1>图书管理</h1>
          <button class="btn-add" @click="openAddBookModal"><i class="icon-add"></i> 添加图书</button>
        </div>

        <div class="search-bar">
          <input type="text" v-model="bookSearchKeyword" placeholder="搜索书名或作者..." />
          <button class="btn-search" @click="fetchBooks"><i class="icon-search"></i> 搜索</button>
        </div>

        <div class="table-container">
          <table class="book-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>书名</th>
                <th>作者</th>
                <th>ISBN</th>
                <th>分类</th>
                <th>库存</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="book in books" :key="book.id">
                <td>{{ book.id }}</td>
                <td>{{ book.title }}</td>
                <td>{{ book.author }}</td>
                <td>{{ book.isbn }}</td>
                <td>{{ book.category }}</td>
                <td>{{ book.stock }}</td>
                <td>
                  <span :class="['status-badge', book.status === 'available' ? 'status-active' : 'status-inactive']">
                    {{ book.status === 'available' ? '可借阅' : '不可借阅' }}
                  </span>
                </td>
                <td class="action-buttons">
                  <button class="btn-edit" @click="openEditBookModal(book)"><i class="icon-edit"></i> 编辑</button>
                  <button class="btn-delete" @click="confirmDeleteBook(book.id)"><i class="icon-delete"></i> 删除</button>
                </td>
              </tr>
              <tr v-if="books.length === 0 && !bookLoading">
                <td colspan="8" class="no-data">暂无图书数据</td>
              </tr>
              <tr v-if="bookLoading">
                <td colspan="8" class="loading">加载中...</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="pagination" v-if="bookTotalPages > 1">
          <button @click="changeBookPage(1)" :disabled="bookCurrentPage === 1">首页</button>
          <button @click="changeBookPage(bookCurrentPage - 1)" :disabled="bookCurrentPage === 1">上一页</button>
          <span>第 {{ bookCurrentPage }} 页 / 共 {{ bookTotalPages }} 页</span>
          <button @click="changeBookPage(bookCurrentPage + 1)" :disabled="bookCurrentPage === bookTotalPages">下一页</button>
          <button @click="changeBookPage(bookTotalPages)" :disabled="bookCurrentPage === bookTotalPages">末页</button>
        </div>
      </div>

      <!-- 用户添加/编辑模态框 -->
      <div class="modal-overlay" v-if="showUserModal">
        <div class="modal">
          <div class="modal-header">
            <h2>{{ isEditUserMode ? '编辑用户' : '添加用户' }}</h2>
            <button class="modal-close" @click="closeUserModal">&times;</button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="submitUserForm">
              <div class="form-group">
                <label>用户名:</label>
                <input type="text" v-model="userFormData.username" required />
              </div>
              <div class="form-group">
                <label>邮箱:</label>
                <input type="email" v-model="userFormData.email" required />
              </div>
              <div class="form-group">
                <label>密码:</label>
                <input type="password" v-model="userFormData.password" :required="!isEditUserMode" />
                <span class="form-hint" v-if="isEditUserMode">不修改密码请留空</span>
              </div>
              <div class="form-group">
                <label>角色:</label>
                <select v-model="userFormData.role" required>
                  <option value="user">普通用户</option>
                  <option value="admin">管理员</option>
                </select>
              </div>
              <div class="form-group">
                <label>状态:</label>
                <select v-model="userFormData.status" required>
                  <option value="active">启用</option>
                  <option value="inactive">禁用</option>
                </select>
              </div>
              <div class="form-actions">
                <button type="button" class="btn-cancel" @click="closeUserModal">取消</button>
                <button type="submit" class="btn-save">{{ isEditUserMode ? '更新' : '保存' }}</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- 图书添加/编辑模态框 -->
      <div class="modal-overlay" v-if="showBookModal">
        <div class="modal">
          <div class="modal-header">
            <h2>{{ isEditBookMode ? '编辑图书' : '添加图书' }}</h2>
            <button class="modal-close" @click="closeBookModal">&times;</button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="submitBookForm">
              <div class="form-group">
                <label>书名:</label>
                <input type="text" v-model="bookFormData.title" required />
              </div>
              <div class="form-group">
                <label>作者:</label>
                <input type="text" v-model="bookFormData.author" required />
              </div>
              <div class="form-group">
                <label>ISBN:</label>
                <input type="text" v-model="bookFormData.isbn" required />
              </div>
              <div class="form-group">
                <label>分类:</label>
                <select v-model="bookFormData.category" required>
                  <option value="fiction">小说</option>
                  <option value="non-fiction">非小说</option>
                  <option value="science">科学</option>
                  <option value="history">历史</option>
                  <option value="biography">传记</option>
                  <option value="other">其他</option>
                </select>
              </div>
              <div class="form-group">
                <label>库存:</label>
                <input type="number" v-model="bookFormData.stock" min="0" required />
              </div>
              <div class="form-group">
                <label>状态:</label>
                <select v-model="bookFormData.status" required>
                  <option value="available">可借阅</option>
                  <option value="unavailable">不可借阅</option>
                </select>
              </div>
              <div class="form-actions">
                <button type="button" class="btn-cancel" @click="closeBookModal">取消</button>
                <button type="submit" class="btn-save">{{ isEditBookMode ? '更新' : '保存' }}</button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- 删除确认模态框 -->
      <div class="modal-overlay" v-if="showDeleteConfirm">
        <div class="modal confirm-modal">
          <div class="modal-header">
            <h2>确认删除</h2>
            <button class="modal-close" @click="showDeleteConfirm = false">&times;</button>
          </div>
          <div class="modal-body">
            <p>确定要删除{{ deleteType === 'user' ? '用户' : '图书' }}ID为 {{ deleteId }} 的记录吗？此操作不可撤销。</p>
            <div class="form-actions">
              <button class="btn-cancel" @click="showDeleteConfirm = false">取消</button>
              <button class="btn-delete" @click="confirmDelete()">{{ deleteType === 'user' ? '删除用户' : '删除图书' }}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { userService } from '@/services/userService';
import bookService from '@/services/bookService';

// 标签页状态
const currentTab = ref('user');

// 用户管理状态
const users = ref([]);
const userLoading = ref(false);
const searchKeyword = ref('');
const userCurrentPage = ref(1);
const userPageSize = ref(10);
const userTotalPages = ref(1);
const userTotalCount = ref(0);

// 用户模态框状态
const showUserModal = ref(false);
const isEditUserMode = ref(false);
const userFormData = ref({
  username: '',
  email: '',
  password: '',
  role: 'user',
  status: 'active'
});

// 图书管理状态
const books = ref([]);
const bookLoading = ref(false);
const bookSearchKeyword = ref('');
const bookCurrentPage = ref(1);
const bookPageSize = ref(10);
const bookTotalPages = ref(1);
const bookTotalCount = ref(0);

// 图书模态框状态
const showBookModal = ref(false);
const isEditBookMode = ref(false);
const bookFormData = ref({
  title: '',
  author: '',
  isbn: '',
  category: 'fiction',
  stock: 0,
  status: 'available'
});

// 删除确认状态
const showDeleteConfirm = ref(false);
const deleteId = ref(null);
const deleteType = ref('user');

// 生命周期钩子
onMounted(() => {
  fetchUsers();
});

// 切换标签页时加载对应数据
watch(currentTab, (newTab) => {
  if (newTab === 'user' && users.value.length === 0) {
    fetchUsers();
  } else if (newTab === 'book' && books.value.length === 0) {
    fetchBooks();
  }
});

// 用户管理方法
const fetchUsers = async () => {
  try {
    userLoading.value = true;
    const params = {
      page: userCurrentPage.value - 1,
      size: userPageSize.value
    };
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }
    const response = await userService.getUsers(params);
    users.value = response.data?.data || [];
    userTotalCount.value = response.data?.total || 0;
    userTotalPages.value = Math.ceil(userTotalCount.value / userPageSize.value);
  } catch (error) {
    console.error('获取用户列表失败:', error);
    alert('获取用户数据失败，请重试');
  } finally {
    userLoading.value = false;
  }
};

const openAddUserModal = () => {
  isEditUserMode.value = false;
  userFormData.value = {
    username: '',
    email: '',
    password: '',
    role: 'user',
    status: 'active'
  };
  showUserModal.value = true;
};

const openEditUserModal = (user) => {
  isEditUserMode.value = true;
  userFormData.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    password: '',
    role: user.role,
    status: user.status
  };
  showUserModal.value = true;
};

const closeUserModal = () => {
  showUserModal.value = false;
};

const submitUserForm = async () => {
  try {
    if (isEditUserMode.value) {
      await userService.updateUser(userFormData.value.id, userFormData.value);
      alert('用户更新成功');
    } else {
      await userService.createUser(userFormData.value);
      alert('用户添加成功');
    }
    closeUserModal();
    fetchUsers();
  } catch (error) {
    console.error(isEditUserMode.value ? '更新用户失败:' : '添加用户失败:', error);
    alert(isEditUserMode.value ? '更新用户失败，请重试' : '添加用户失败，请重试');
  }
};

const confirmDeleteUser = (userId) => {
  deleteId.value = userId;
  deleteType.value = 'user';
  showDeleteConfirm.value = true;
};

const changeUserPage = (page) => {
  if (page >= 1 && page <= userTotalPages.value) {
    userCurrentPage.value = page;
    fetchUsers();
  }
};

// 图书管理方法
const fetchBooks = async () => {
  try {
    bookLoading.value = true;
    const params = {
      page: bookCurrentPage.value - 1,
      size: bookPageSize.value
    };
    if (bookSearchKeyword.value) {
      params.title = bookSearchKeyword.value;
      params.author = bookSearchKeyword.value;
      params.isbn = bookSearchKeyword.value;
    }
    const response = await bookService.getBooks(params);
    books.value = response.data?.data || [];
    bookTotalCount.value = response.data?.total || 0;
    bookTotalPages.value = Math.ceil(bookTotalCount.value / bookPageSize.value);
  } catch (error) {
    console.error('获取图书列表失败:', error);
    alert('获取图书数据失败，请重试');
  } finally {
    bookLoading.value = false;
  }
};

const openAddBookModal = () => {
  isEditBookMode.value = false;
  bookFormData.value = {
    title: '',
    author: '',
    isbn: '',
    category: 'fiction',
    stock: 0,
    status: 'available'
  };
  showBookModal.value = true;
};

const openEditBookModal = (book) => {
  isEditBookMode.value = true;
  bookFormData.value = {
    id: book.id,
    title: book.title,
    author: book.author,
    isbn: book.isbn,
    category: book.category,
    stock: book.stock,
    status: book.status
  };
  showBookModal.value = true;
};

const closeBookModal = () => {
  showBookModal.value = false;
};

const submitBookForm = async () => {
  try {
    if (isEditBookMode.value) {
      await bookService.updateBook(bookFormData.value.id, bookFormData.value);
      alert('图书更新成功');
    } else {
      await bookService.createBook(bookFormData.value);
      alert('图书添加成功');
    }
    closeBookModal();
    fetchBooks();
  } catch (error) {
    console.error(isEditBookMode.value ? '更新图书失败:' : '添加图书失败:', error);
    alert(isEditBookMode.value ? '更新图书失败，请重试' : '添加图书失败，请重试');
  }
};

const confirmDeleteBook = (bookId) => {
  deleteId.value = bookId;
  deleteType.value = 'book';
  showDeleteConfirm.value = true;
};

const confirmDelete = async () => {
  try {
    if (deleteType.value === 'user') {
      await userService.deleteUser(deleteId.value);
      alert('用户删除成功');
      fetchUsers();
    } else {
      await bookService.deleteBook(deleteId.value);
      alert('图书删除成功');
      fetchBooks();
    }
    showDeleteConfirm.value = false;
  } catch (error) {
    console.error(deleteType.value === 'user' ? '删除用户失败:' : '删除图书失败:', error);
    alert(deleteType.value === 'user' ? '删除用户失败，请重试' : '删除图书失败，请重试');
  }
};

const changeBookPage = (page) => {
  if (page >= 1 && page <= bookTotalPages.value) {
    bookCurrentPage.value = page;
    fetchBooks();
  }
};
</script>

<style scoped>
.admin-container {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 220px;
  background-color: #2c3e50;
  color: white;
  height: 100vh;
  position: fixed;
  box-shadow: 2px 0 5px rgba(0,0,0,0.1);
}

.sidebar-menu {
  padding-top: 20px;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.menu-item:hover {
  background-color: #34495e;
}

.menu-item.active {
  background-color: #3498db;
  border-left: 4px solid #2980b9;
}

.menu-item i {
  margin-right: 10px;
  font-size: 16px;
}

.main-content {
  flex: 1;
  margin-left: 220px;
  padding: 24px;
  max-width: calc(100% - 220px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.btn-add {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.btn-add i {
  margin-right: 5px;
}

.btn-add:hover {
  background-color: #359469;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-bar input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn-search {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.btn-search i {
  margin-right: 5px;
}

.table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

.user-table, .book-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e9e9e9;
}

.user-table th, .user-table td, .book-table th, .book-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #e9e9e9;
}

.user-table th, .book-table th {
  background-color: #f5f5f5;
  font-weight: bold;
  color: #333;
}

.user-table tr:hover, .book-table tr:hover {
  background-color: #f9f9f9;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.status-active {
  background-color: #dff0d8;
  color: #3c763d;
}

.status-inactive {
  background-color: #f2dede;
  color: #a94442;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-edit {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.btn-edit i {
  margin-right: 3px;
}

.btn-delete {
  background-color: #dc3545;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.btn-delete i {
  margin-right: 3px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
}

.pagination button {
  background-color: #fff;
  border: 1px solid #ddd;
  padding: 4px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.no-data, .loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.confirm-modal {
  width: 350px;
}

.modal-header {
  padding: 16px;
  border-bottom: 1px solid #e9e9e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 18px;
}

.modal-close {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 16px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  font-size: 14px;
}

.form-group input, .form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-hint {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
  display: block;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 24px;
}

.btn-cancel {
  background-color: #fff;
  border: 1px solid #ddd;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-save {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}
</style>
--- 功能：管理员后台入口界面
- 特性：当前为基础框架（仅包含欢迎信息），可扩展管理功能
- 用途：后续管理员操作（如用户管理、图书审核）的入口